// SplashScreen.cs
// 
// Copyright © 2009 FreeZzaph
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using Gtk;
using System;
using System.Threading;
using FreeZzaphGUI;
	
public partial class SplashScreen : Gtk.Window, ISplashView
{
	
	private bool _certainState = true;
	private object _certainLock = new object();
	private Thread _pulsateThread;
	
	private void Pulsate()
	{
		bool keepGoing = !_certainState;
		while (keepGoing)
		{
			Application.Invoke((o, e) =>
			{
				Progress.Pulse();
			});
			Thread.Sleep(40);
			
			keepGoing = !_certainState;
		}
	}
	
	public double PercentDone
	{
		set {
			lock (_certainLock)
				if (!_certainState)
					throw new InvalidOperationException("Cannot update percentage when state is not certain");
			
			Application.Invoke((o, e) =>
			{
				Progress.Fraction = value;
			});
		}
	}
	
	public bool CertainState
	{
		set
		{
			lock (_certainLock)
			{
				if (_certainState == value)
					return;
				else
					_certainState = value;
			}
				
			if (_certainState == false)
			{
				_pulsateThread = new Thread(Pulsate);
				_pulsateThread.Start();
			}
			else
			{
				if (_pulsateThread.IsAlive)
					_pulsateThread.Join();
				
				_pulsateThread = null;
				double f = Progress.Fraction;
				
				Application.Invoke((o, e) => {
					Progress.Fraction = f;
				});
			}
		}
	}
	
	public string Message
	{
		set
		{
			Application.Invoke((o, e) =>
			{
				MessageLabel.Text = value;
			});
		}
	}
	
	public void ShowSplash()
	{
		Application.Invoke((o, e) =>
		{
			this.Show();
		});
	}
	
	public void HideSplash()
	{
		Application.Invoke((o, e) =>
		{
			this.Hide();
		});
	}
	
	public SplashScreen() : 
			base(Gtk.WindowType.Toplevel)
	{
		this.Build();
	}
}
